package master;

/**
 * @author chenyw
 * @date 2022/7/30 19:27
 */
public class M110isBalanced {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        return dfs(root) == -1 ? false : true;
    }

    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left, right;
        if ((left = dfs(root.left)) == -1 || (right = dfs(root.right)) == -1 || Math.abs(left - right) > 1) {
            return -1;
        } else {
            return Math.max(left, right) + 1;
        }
    }
}
